﻿using System;
using MaQiu.SqlExecute.DbProvider;
using System.Reflection;

namespace MaQiu.SqlExecute.DAL
{
    internal class SqlConnection : IDisposable
    {
        public static bool IsSingleThreadExec = false;
        internal static object LockObject = new object();

        [ThreadStatic]
        private static string _connectionString;

        [ThreadStatic]
        private static SqlConnectionInternal _conn;

        [ThreadStatic]
        public static IDbProvider Provider;

        public SqlConnection(TransactionMode mode)
        {
            Init(mode);
        }

        public SqlConnection()
        {
            Init(TransactionMode.Inherit);
        }

        public void Dispose()
        {
            if (_conn == null || _conn.PopTransactionMode()) return;
            try
            {
                _conn.Dispose();
            }
            catch
            {
                // ignored
            }
            finally
            {
                _conn = null;
            }
        }

        public void Commit()
        {
            _conn.Commit();
        }

        public void Rollback()
        {
            _conn.Rollback();
        }

        internal SqlConnectionInternal GetConnection()
        {
            return _conn;
        }

        private void Init(TransactionMode mode)
        {
            if (_conn != null)
            {
                _conn.PushTransactionMode(mode);
            }
            else
            {
                _conn = new SqlConnectionInternal(_connectionString, Provider);
                _conn.PushTransactionMode(mode);
            }
        }

        public static void InitSqlExecute(string connectString, IDbProvider provider)
        {
            _connectionString = connectString;
            Provider = provider;
        }

        public static void InitSqlServerExecute(string server, string userName, string password, string database)
        {
            _connectionString = "server=" + server + ";uid=" + userName + ";pwd=" + password + ";database=" + database + "";
            Provider = new SqlServerProvider();
        }
    }

    public enum TransactionMode
    {
        Required = 1,
        Inherit = 0
    }
}